var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var morgan = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');

//载入应用配置
var config = require('./config/config');
var app = express();

/*session由mongodb缓存*/
var session = require('express-session');
var mongoStore = require('connect-mongo')(session);

app.use(session({
  name: 'MyBlogSession',
  secret: 'MyBlogKey',
  resave: false,
  saveUninitialized: true,
  cookie: {
    maxAge: 3 * 24 * 60 * 60 * 1000 //3天
  },
  store: new mongoStore({ url: config.mongodb })
}));

// view engine setup
app.set('views', path.join(__dirname, 'frontEnd/views'));
app.set('view engine', 'jade');

// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(morgan('dev'));
app.use(bodyParser.json({ limit: '50mb' }));
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());

if (process.env.NODE_ENV === 'production') {
  app.use('/css', express.static(path.join(__dirname, 'frontEnd/css')));
  app.use('/js', express.static(path.join(__dirname, 'frontEnd/js')));
} else {
  app.use('/css', express.static(path.join(__dirname, 'frontEnd/css_dev')));
  app.use('/js', express.static(path.join(__dirname, 'frontEnd/js_dev')));
}

app.use(express.static(path.join(__dirname, 'frontEnd')));
app.use('/lib', express.static(path.join(__dirname, 'frontEnd/lib')));
app.use('/template', express.static(path.join(__dirname, 'frontEnd/views/public/template')));
app.use('/admin/template', express.static(path.join(__dirname, 'frontEnd/views/admin/template')));
app.use('/resource', express.static(path.join(__dirname, 'resource')));



//路由访问写入日志
var logger = require('./utils/log');
app.use(function(req, res, next) {
  logger.logInfo({ url: req.originalUrl, method: req.method, params: req.params, query: req.query });
  next();
});

//  路由配置
var index = require('./routes/index');
var admin = require('./routes/admin');
var api = require('./routes/api');
app.use('/', index);
app.use('/admin', admin);
app.use('/api', api);


// catch 404 and forward to error handler
app.use(function(req, res, next) {
  var err = new Error('Not Found');
  err.status = 404;
  next(err);
});

// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

module.exports = app;